package cn.mumzone.pos.ui.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.AppCompatImageView;
import android.support.v7.widget.RecyclerView;
import android.text.InputType;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.mumzone.basic.adapter.TextWatcherAdapter;
import cn.mumzone.basic.base.BaseActivity;
import cn.mumzone.basic.loading.button.LoadingButton;
import cn.mumzone.basic.util.BigDecimalUtil;
import cn.mumzone.basic.util.EditTextUtil;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.NetUtil;
import cn.mumzone.basic.util.PosToast;
import cn.mumzone.basic.util.RxBus;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.R;
import cn.mumzone.pos.dialog.PosAlertDialog;
import cn.mumzone.pos.event.RedeemSuccessEvent;
import cn.mumzone.pos.model.GoodsEntity;
import cn.mumzone.pos.presenter.RedeemPresenter;
import cn.mumzone.pos.presenter.contract.RedeemContract;
import cn.mumzone.pos.ui.adapter.ADA_CartGoodRedeem;
import cn.mumzone.pos.ui.adapter.ADA_GoodsRedeem;
import cn.mumzone.pos.ui.widgets.others.FullyGridLayoutManager;
import cn.mumzone.pos.ui.widgets.others.FullyLinearLayoutManager;
import cn.mumzone.pos.ui.widgets.refresh.SmartRefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.api.RefreshLayout;
import cn.mumzone.pos.ui.widgets.refresh.listener.OnRefreshListener;
import cn.mumzone.pos.ui.widgets.shopping.AnimShopButton;
import cn.mumzone.pos.util.GoodsUtil;

/**
 * Created by qiuzhenhuan on 2019/9/18.
 */

public class ACT_Redeem extends BaseActivity<RedeemPresenter> implements RedeemContract.View {

    private static final String KEY_MEMBER_ID = "member_id";
    private static final String KEY_MEMBER_PHONE = "member_phone";
    private static final String KEY_MEMBER_INTEGRAL = "member_integral";
    private static final String KEY_FROM_SETTLE = "is_from_settle";
    public static final String KEY_REDEEM_GOODS = "redeem_goods";

    @BindView(R.id.et_search_goods)
    EditText etSearch;
    @BindView(R.id.et_scan)
    EditText etScan;
    @BindView(R.id.iv_clear_input)
    AppCompatImageView ivClearInput;
    @BindView(R.id.rb_search)
    RadioButton rbSearch;

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_redeem_goods)
    LRecyclerView rvRedeemGoods;

    @BindView(R.id.ll_empty_goods)
    LinearLayout llEmptyGoods;
    @BindView(R.id.iv_empty_goods)
    AppCompatImageView ivEmptyGoods;
    @BindView(R.id.tv_goods_empty)
    TextView tvGoodsEmpty;
    @BindView(R.id.tv_goods_empty_hint)
    TextView tvGoodsEmptyHint;

    @BindView(R.id.tv_integral)
    TextView tvIntegral;

    @BindView(R.id.rv_cart_goods)
    RecyclerView rvCartGoods;
    @BindView(R.id.ll_cart_goods)
    LinearLayout llCartGoods;
    @BindView(R.id.ll_empty_cart)
    LinearLayout llEmptyCart;

    @BindView(R.id.tv_select_count)
    TextView tvSelectCount;
    @BindView(R.id.tv_select_price)
    TextView tvSelectPrice;
    @BindView(R.id.btn_settle)
    LoadingButton lbSettle;


    private ADA_GoodsRedeem mGoodsRedeemAdapter;
    private LRecyclerViewAdapter mLGoodsAdapter;
    private ADA_CartGoodRedeem mCartRedeemAdapter;

    private List<GoodsEntity> localCartGoods = new ArrayList<>();

    private String memberId;
    private String phone;
    private String integral;

    private String keyword = "";

    private boolean isFromSettle;

    private boolean isScanExecuted = false;

    @Override
    protected void getBundleExtras(Bundle extras) {
        super.getBundleExtras(extras);
        memberId = extras.getString(KEY_MEMBER_ID);
        phone = extras.getString(KEY_MEMBER_PHONE);
        integral = extras.getString(KEY_MEMBER_INTEGRAL);
        isFromSettle = extras.getBoolean(KEY_FROM_SETTLE, false);
        if (isFromSettle) {
            localCartGoods = (List<GoodsEntity>) extras.getSerializable(KEY_REDEEM_GOODS);
        }
    }

    @Override
    protected void initEventAndData() {

        initScanView();

        toggleEmptyLayout(false, false);

        tvIntegral.setText(StringUtils.getWholeNumber(integral));

        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                mPresenter.loadGoodsList(keyword, true);
            }
        });

        mGoodsRedeemAdapter = new ADA_GoodsRedeem(mContext);
        mGoodsRedeemAdapter.setOnItemClickedListener(new ADA_GoodsRedeem.OnItemClickedListener() {
            @Override
            public void onItemClicked(int position) {
                GoodsEntity goodsEntity = mGoodsRedeemAdapter.getDataList().get(position - 1);
                if (!StringUtils.isTrue(goodsEntity.getStockGoods())) {
                    addToCart(goodsEntity);
                } else {
                    showError("商品未入库，无法售卖~");
                }
            }
        });
        rvRedeemGoods.setLayoutManager(new FullyGridLayoutManager(mContext, 3));
        rvRedeemGoods.setPullRefreshEnabled(false);
        mLGoodsAdapter = new LRecyclerViewAdapter(mGoodsRedeemAdapter);
        rvRedeemGoods.setAdapter(mLGoodsAdapter);
        rvRedeemGoods.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                String keyword = etSearch.getText().toString().trim();
                mPresenter.loadGoodsList(keyword, false);
            }
        });

        rvCartGoods.setLayoutManager(new FullyLinearLayoutManager(mContext));
        mCartRedeemAdapter = new ADA_CartGoodRedeem(mContext);
        mCartRedeemAdapter.setOnGoodsAmountChangedListener(new ADA_CartGoodRedeem.OnGoodsAmountChangedListener() {
            @Override
            public void onAmountChanged(GoodsEntity entity, AnimShopButton view, int count) {

                if (getTotalIntegral() + Integer.parseInt(entity.getIntegral()) > Integer.parseInt(integral)) {
                    showError("积分不足");
                    view.setCount(count - 1);
                    return;
                }

                entity.setGoodsCount(String.valueOf(count));
                updateCountAndTotalPrice();
            }

            @Override
            public void onGoodsDeleted(final int position) {

                new PosAlertDialog.Builder(mContext)
                        .setRemindText("确认要删除商品吗？")
                        .setOnConfirmClickListener(new PosAlertDialog.OnConfirmClickListener() {
                            @Override
                            public void onConfirmClick(View view, Dialog dialog) {
                                GoodsEntity mDeletedEntity = mCartRedeemAdapter.getDataList().get(position);
                                mDeletedEntity.setSelectCount(0);
                                localCartGoods.remove(position);
                                mCartRedeemAdapter.update(localCartGoods, true);
                                mCartRedeemAdapter.notifyDataSetChanged();
                                PosToast.INSTANCE.makeCheckMarkToast(mContext, "已删除");
                                updateCountAndTotalPrice();

                                showCartEmpty(ListUtil.isListEmpty(localCartGoods));
                            }
                        }).build().show();

            }
        });
        rvCartGoods.setAdapter(mCartRedeemAdapter);

        refreshLayout.autoRefresh();

        showCartEmpty(ListUtil.isListEmpty(localCartGoods));

        if (isFromSettle) {
            mCartRedeemAdapter.update(localCartGoods, true);
            updateCountAndTotalPrice();
        }

    }

    private void showCartEmpty(boolean isShowEmpty) {
        if (isShowEmpty) {
            llCartGoods.setVisibility(View.GONE);
            llEmptyCart.setVisibility(View.VISIBLE);
        } else {
            llCartGoods.setVisibility(View.VISIBLE);
            llEmptyCart.setVisibility(View.GONE);
        }
    }

    private void addToCart(GoodsEntity goodsEntity) {

        if (getTotalIntegral() + Integer.parseInt(goodsEntity.getIntegral()) > Integer.parseInt(integral)) {
            showError("积分不足");
            return;
        }

        showCartEmpty(false);


        if (!localCartGoods.isEmpty()) {
            boolean isFindInData = false;
            for (GoodsEntity localEntity : localCartGoods) {
                if (goodsEntity.getGoodsId().equals(localEntity.getGoodsId())) {
                    isFindInData = true;
                    localEntity.setGoodsCount(String.valueOf(Integer.parseInt(localEntity.getGoodsCount()) + 1));
                    break;
                }
            }
            if (!isFindInData) {
                goodsEntity.setGoodsCount("1");
                localCartGoods.add(goodsEntity.clone());
            }
        } else {
            goodsEntity.setGoodsCount("1");
            localCartGoods.add(goodsEntity.clone());
        }
        mCartRedeemAdapter.update(localCartGoods, true);
        mCartRedeemAdapter.notifyDataSetChanged();

        updateCountAndTotalPrice();
    }

    private void updateCountAndTotalPrice() {

        int totalCount = 0;
        for (GoodsEntity goodsEntity : mCartRedeemAdapter.getDataList()) {
            totalCount += Integer.parseInt(goodsEntity.getGoodsCount());
        }
        tvSelectCount.setText(String.valueOf(totalCount));

        int totalIntegral = getTotalIntegral();
        tvSelectPrice.setText(String.format("%s积分", String.valueOf(totalIntegral)));

        tvIntegral.setText(StringUtils.getWholeNumber(String.valueOf(BigDecimalUtil.sub(integral, String.valueOf(totalIntegral)))));
    }

    private int getTotalIntegral() {
        if (ListUtil.isListEmpty(localCartGoods)) {
            return 0;
        }

        int totalIntegral = 0;
        for (GoodsEntity localGoods : localCartGoods) {
            totalIntegral += Integer.parseInt(BigDecimalUtil.getNumber(localGoods.getIntegral())) * Integer.parseInt(BigDecimalUtil.getNumber(localGoods.getGoodsCount()));
        }
        return totalIntegral;
    }

    private void initScanView() {

        etScan.setInputType(InputType.TYPE_NULL);
        etScan.requestFocus();
        EditTextUtil.hideSoftInputMethod(mContext, etScan);
        GoodsUtil.initScanForGoodsSold(mContext, etScan, etSearch, new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                String code = v.getText().toString().trim();
                if (actionId == KeyEvent.ACTION_DOWN && !TextUtils.isEmpty(code)) {

                    if (!NetUtil.isNetworkAvailable(mContext)) {
                        PosToast.INSTANCE.makeShortToast(mContext, "网络不给力，请稍候再试");
                        return true;
                    }

                    if (!isScanExecuted) {
                        mPresenter.loadGoodsList(code, true);
                    }
                    etScan.setText("");
                    isScanExecuted = true;
                }
                return true;
            }
        }, new TextWatcherAdapter() {
            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                super.onTextChanged(charSequence, i, i1, i2);
                boolean isInputNotEmpty = !TextUtils.isEmpty(etSearch.getText().toString());
                ivClearInput.setVisibility(isInputNotEmpty ? View.VISIBLE : View.GONE);
                rbSearch.setEnabled(isInputNotEmpty);
                rbSearch.setChecked(isInputNotEmpty);
            }
        });

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    EditTextUtil.hideSoftInput(mContext, v);

                    refreshLayout.autoRefresh();
                }
                return false;
            }
        });
    }

    @OnClick({R.id.rb_search, R.id.btn_settle, R.id.iv_clear_input})
    void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rb_search:
                keyword = etSearch.getText().toString().trim();
                refreshLayout.autoRefresh();
                etSearch.clearFocus();
                etScan.requestFocus();
                break;
            case R.id.btn_settle:
                if (isFromSettle) {
                    Intent intent = new Intent();
                    intent.putExtra(KEY_REDEEM_GOODS, (Serializable) localCartGoods);
                    setResult(RESULT_OK, intent);
                    finish();
                } else {
                    lbSettle.startLoading("正在完成...", rvRedeemGoods, rvCartGoods);
                    mPresenter.doRedeemGoods(memberId, phone, String.valueOf(getTotalIntegral()), localCartGoods);
                }

                break;
            case R.id.iv_clear_input:
                keyword = "";
                etSearch.setText("");
                etSearch.clearFocus();
                etScan.requestFocus();
                break;
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.act_redeem;
    }


    public static void startAc(Context context, String memberId, String phone, String integral) {
        Intent intent = new Intent(context, ACT_Redeem.class);
        intent.putExtra(KEY_MEMBER_ID, memberId);
        intent.putExtra(KEY_MEMBER_PHONE, phone);
        intent.putExtra(KEY_MEMBER_INTEGRAL, integral);
        intent.putExtra(KEY_FROM_SETTLE, false);
        context.startActivity(intent);
    }

    public static void startAcForResult(Activity activity, String integral,
                                        List<GoodsEntity> redeemGoods, int requestCode) {
        Intent intent = new Intent(activity, ACT_Redeem.class);
        intent.putExtra(KEY_MEMBER_INTEGRAL, integral);
        intent.putExtra(KEY_REDEEM_GOODS, (Serializable) redeemGoods);
        intent.putExtra(KEY_FROM_SETTLE, true);
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    public void showSearchGoodsList(List<GoodsEntity> list, boolean isRefresh) {
        etSearch.clearFocus();
        etScan.requestFocus();
        rvRedeemGoods.refreshComplete(AppConstants.PAGE_SIZE);
        refreshLayout.finishRefresh();
        if (isScanExecuted) {
            isScanExecuted = false;

            if (!ListUtil.isListEmpty(list) && list.size() == 1) {
                addToCart(list.get(0));
                return;
            }
        }

        mGoodsRedeemAdapter.update(list, isRefresh);
        mLGoodsAdapter.notifyDataSetChanged();

        if (ListUtil.isListEmpty(mGoodsRedeemAdapter.getDataList())) {
            toggleEmptyLayout(true, false);
        } else {
            toggleEmptyLayout(false, false);
        }

    }

    @Override
    public void showRedeemGoodSuccess() {
        lbSettle.stopLoading("确认");
        PosToast.INSTANCE.makeSuccessToast(mContext, "换购成功");
        if (!isFromSettle) {
            RxBus.getDefault().post(new RedeemSuccessEvent());
        }
        finish();
    }

    @Override
    public void showSearchGoodsError(String msg) {
        etSearch.clearFocus();
        etScan.requestFocus();
        if (isScanExecuted) {
            isScanExecuted = false;
            PosToast.INSTANCE.makeShortToast(mContext, msg);
            return;
        }

        if (refreshLayout != null) {
            refreshLayout.finishRefresh();
        }
        rvRedeemGoods.refreshComplete(AppConstants.PAGE_SIZE);

        toggleEmptyLayout(true, false);
    }

    @Override
    public void showError(String msg) {
        refreshLayout.finishRefresh();
        rvRedeemGoods.refreshComplete(AppConstants.PAGE_SIZE);
        lbSettle.stopLoading("确认");
        super.showError(msg);
    }

    public void toggleEmptyLayout(boolean isEmpty, boolean isDataEmpty) {
        if (isEmpty) {
            llEmptyGoods.setVisibility(View.VISIBLE);
            rvRedeemGoods.setVisibility(View.GONE);

            ivEmptyGoods.setImageResource(isDataEmpty ? R.mipmap.ic_cash_service_empty : R.mipmap.ic_cash_service_empty_search);
            tvGoodsEmpty.setText(isDataEmpty ? "暂无商品信息" : "没有找到任何内容");
            tvGoodsEmptyHint.setText(isDataEmpty ? "您可以在后台配置商品信息" : "你可以换个关键词试试~");
            tvGoodsEmptyHint.setTextColor(isDataEmpty ? getResources().getColor(R.color.order_status_service) :
                    getResources().getColor(R.color.content_text_color));
            tvGoodsEmptyHint.setCompoundDrawablesWithIntrinsicBounds(isDataEmpty ?
                            getResources().getDrawable(R.drawable.svg_ic_alert_remind) : null,
                    null, null, null);

        } else {
            // 商品信息 + 空页面
            llEmptyGoods.setVisibility(View.GONE);
            rvRedeemGoods.setVisibility(View.VISIBLE);
        }
    }

}
